package com.huanxi.joytravel.bases;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowInsets;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.core.view.ViewCompat;

import com.huanxi.joytravel.R;
import com.huanxi.joytravel.utils.NetWatchdogUtils;
import com.huanxi.joytravel.utils.StatusBarUtils;
import com.huanxi.joytravel.utils.ToastUtil;
import com.huanxi.joytravel.widgets.LoadingDialog;
import com.huanxi.joytravel.widgets.ProgressLinearLayout;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import pub.devrel.easypermissions.EasyPermissions;

public abstract class BaseActivity extends AppCompatActivity {
    public Context mContext;
    private int count = -1;
    protected String TAG = null;
    private Unbinder unbinder;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        TAG = getClass().getSimpleName();
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            //结束你的activity
            finish();
            return;
        }
        unbinder = ButterKnife.bind(this);
        mContext = this;
        AppManager.getAppManager().addActivity(this);
        if (!NetWatchdogUtils.hasNet(mContext)) {
            ToastUtil.showNorToast("网络未连接");
        }
        init();
    }

    public void setStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            View decorView = window.getDecorView();
            decorView.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
                @TargetApi(Build.VERSION_CODES.KITKAT_WATCH)
                @Override
                public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
                    WindowInsets defaultInsets = v.onApplyWindowInsets(insets);
                    return defaultInsets.replaceSystemWindowInsets(
                            defaultInsets.getSystemWindowInsetLeft(),
                            0,
                            defaultInsets.getSystemWindowInsetRight(),
                            defaultInsets.getSystemWindowInsetBottom());
                }
            });
            ViewCompat.requestApplyInsets(decorView);
            //将状态栏设成透明，如不想透明可设置其他颜色
            window.setStatusBarColor(ContextCompat.getColor(this, android.R.color.transparent));
        }
    }

    /*********************
     * 子类实现
     *****************************/
    //获取布局文件
    public abstract int getLayoutId();

    //初始化view
    protected abstract void init();

    /**
     * 通过Class跳转界面
     **/
    public void startActivity(Class<?> cls) {
        startActivity(cls, null);
    }

    /**
     * 含有Bundle通过Class跳转界面
     **/
    public void startActivity(Class<?> cls, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    /**
     * 含有Bundle通过Class跳转界面
     **/
    public void startActivityForResult(Class<?> cls, Bundle bundle,
                                       int requestCode) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
    }

    /**
     * activity动画的设置
     */
    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        overridePendingTransition(R.anim.aim_common_right_in,
                R.anim.aim_common_left_out);
    }


    @Override
    public void startActivityForResult(Intent intent, int requestCode) {
        super.startActivityForResult(intent, requestCode);
        overridePendingTransition(R.anim.aim_common_right_in,
                R.anim.aim_common_left_out);
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.aim_common_left_in,
                R.anim.aim_common_right_out);
    }

    /**
     * activity动画的设置
     */

    public void startActivityByLeft(Intent intent) {
        count = 1;
        startActivity(intent);
        overridePendingTransition(R.anim.aim_common_right_in,
                R.anim.aim_common_left_out);
    }

    public void startActivityByRight(Intent intent) {
        count = 2;
        startActivity(intent);
        overridePendingTransition(R.anim.aim_common_left_in,
                R.anim.aim_common_right_out);
    }

    public void startActivityByUp(Intent intent) {
        count = 3;
        startActivity(intent);
        overridePendingTransition(R.anim.aim_common_down_in,
                R.anim.aim_common_up_out);
    }

    public void startActivityByDown(Intent intent) {
        count = 2;
        startActivity(intent);
        overridePendingTransition(R.anim.aim_common_up_out,
                R.anim.aim_common_down_in);
    }


    public void startActivityForResultByUp(Intent intent, int requestCode) {
        count = 3;
        startActivityForResult(intent, requestCode);
        overridePendingTransition(R.anim.aim_common_down_in,
                R.anim.aim_common_up_out);
    }

    public void startActivityForResultByLeft(Intent intent, int requestCode) {
        count = 1;
        startActivityForResult(intent, requestCode);
        overridePendingTransition(R.anim.aim_common_right_in,
                R.anim.aim_common_left_out);
    }

    public void finishByDown() {
        finish();
        overridePendingTransition(R.anim.aim_common_up_in,
                R.anim.aim_common_down_out);
    }

    public void finishByRight() {
        finish();
        overridePendingTransition(R.anim.aim_common_left_in,
                R.anim.aim_common_right_out);
    }

    /**
     * 着色状态栏（4.4以上系统有效）
     */
    protected void SetStatusBarColor() {
        StatusBarUtils.setStatusBarColor(this, ContextCompat.getColor(this, R.color.colorAccent));
    }

    /**
     * 着色状态栏（4.4以上系统有效）
     */
    protected void SetStatusBarColor(int color) {
        StatusBarUtils.setStatusBarColor(this, color);
    }

    /**
     * 沉浸状态栏（4.4以上系统有效）
     */
    protected void SetTransparentBar() {
        StatusBarUtils.translucentStatusBar(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (count == 1) {
                finishByRight();
            } else if (count == 2) {
                finishByDown();
            } else if (count == 3) {
                finish();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 开启浮动加载进度条
     */
    public void startProgressDialog() {
        LoadingDialog.showDialogForLoading(this);
    }

    /**
     * 开启浮动加载进度条
     *
     * @param msg
     */
    public void startProgressDialog(String msg) {
        LoadingDialog.showDialogForLoadingDialog(this, msg, true);
    }

    /**
     * 停止浮动加载进度条
     */
    public void stopProgressDialog() {
        LoadingDialog.cancelDialogForLoading();
    }

    /**
     * 短暂显示Toast提示(来自String)
     **/
    public void showShortToast(String text) {
        ToastUtil.showNorToast(text);
    }

    /**
     * 短暂显示Toast提示(id)
     **/
    public void showShortToast(int resId) {
        ToastUtil.showShort(resId);
    }

    /**
     * 长时间显示Toast提示(来自res)
     **/
    public void showLongToast(int resId) {
        ToastUtil.showLong(resId);
    }

    /**
     * 长时间显示Toast提示(来自String)
     **/
    public void showLongToast(String text) {
        ToastUtil.showLong(text);
    }

    /**
     * 错误页
     *
     * @param progress   布局
     * @param errorTitle 错误文字
     */
    public void showError(ProgressLinearLayout progress, String errorTitle) {
        if (NetWatchdogUtils.hasNet(mContext)) {
            progress.showError(R.mipmap.null_search, errorTitle, "", "点击重试", v -> init());
        } else {
            progress.showError(R.mipmap.null_net, getNetErrString(), "", "点击重试", view -> init());
        }
    }

    /**
     * 展示空内容
     *
     * @param progress   布局
     * @param errorTitle 无内容提示
     */
    public void showEmpty(ProgressLinearLayout progress, String errorTitle) {
        if (NetWatchdogUtils.hasNet(mContext)) {
            progress.showEmpty(R.mipmap.null_search, errorTitle, "");
        } else {
            progress.showEmpty(R.mipmap.null_net, getNetErrString(), "");
        }
    }

    /**
     * 展示内容
     */
    public void showContent(ProgressLinearLayout progress) {
        progress.showContent();
    }

    public String getNetErrString() {
        return this.getResources().getString(R.string.net_err);
    }

    public String getEmptyString() {
        return this.getResources().getString(R.string.request_empty);
    }

    public String getRequestErrString() {
        return this.getResources().getString(R.string.request_err);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
    }
    public Bundle getBundle() {
        Intent intent = getIntent();
        if (intent == null) {
            return new Bundle();
        } else {
            Bundle bundle = intent.getExtras();
            return bundle == null ? new Bundle() : bundle;
        }
    }

    private String staffName() {
        return "三喜客服";
    }

    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        if (newConfig.fontScale != 1)//非默认值
            getResources();
        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (unbinder != null) {
            unbinder.unbind();
            AppManager.getAppManager().removeActivity(this);
        }
    }

}
